// src/utils/request.ts
import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import type { PathRewrite } from './config' // 导入类型
import { config } from './config' // 导入当前环境配置

// 定义响应数据结构（根据你的后端API调整）
export interface ApiResponse<T = any> {
  code: number
  data: T
  message: string
}

// 创建axios实例的工厂函数
export function createAxiosInstance(
  baseURL: string,
  pathRewrite?: PathRewrite // 新增：可选的路径重写规则
): AxiosInstance {
  const instance = axios.create({
    baseURL, // 动态传入的baseURL
    timeout: 10000, // 请求超时时间
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })

  // 请求拦截器
  instance.interceptors.request.use(
    (requestConfig: InternalAxiosRequestConfig) => {
      // 在这里可以添加token等认证信息
      const token = localStorage.getItem('token')
      if (token && requestConfig.headers) {
        requestConfig.headers.Authorization = `Bearer ${token}`
      }

      // 在这里处理路径重写
      const originalUrl = requestConfig.url
      if (pathRewrite && requestConfig.url) {
        for (const [pattern, replacement] of Object.entries(pathRewrite)) {
          const regex = new RegExp(pattern)
          if (regex.test(requestConfig.url)) {
            const beforeRewrite = requestConfig.url
            requestConfig.url = requestConfig.url.replace(regex, replacement)
            console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
            console.log('🔄 路径重写执行:')
            console.log('  规则:', `"${pattern}" → "${replacement}"`)
            console.log('  原始路径:', beforeRewrite)
            console.log('  重写后路径:', requestConfig.url)
            console.log('  完整URL:', `${requestConfig.baseURL}${requestConfig.url}`)
            console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
            break // 通常只匹配一次就够了
          }
        }
      }

      console.log(`📤 [Request] ${requestConfig.method?.toUpperCase()} ${requestConfig.baseURL}${requestConfig.url || originalUrl}`)
      return requestConfig
    },
    (error: any) => {
      return Promise.reject(error)
    }
  )

  // 响应拦截器
  instance.interceptors.response.use(
    (response: AxiosResponse<ApiResponse>) => {
      const { code, data, message } = response.data
      if (code === 0 || code === 200) { // 假设0或200表示成功
        console.log(`✅ [Response] ${response.config.method?.toUpperCase()} ${response.config.url} - 成功`)
        return data
      } else {
        // 处理业务错误
        console.error(`❌ [Response Error] ${message}`)
        // 可以在这里使用Element Plus或Ant Design Vue的Message组件显示错误
        return Promise.reject(new Error(message || '请求失败'))
      }
    },
    (error: any) => {
      // 处理HTTP错误
      const status = error.response?.status
      const message = error.response?.data?.message || error.message

      console.error(`❌ [HTTP Error] ${status || 'Network Error'}: ${message}`)

      // 处理 401 未授权错误
      if (status === 401) {
        console.warn('⚠️ [鉴权] Token 已过期或无效，清除认证信息并跳转登录页')
        
        // 动态导入，避免循环依赖
        import('../utils/auth').then(({ clearAuth }) => {
          clearAuth()
          
          // 跳转到登录页（只在浏览器环境中执行）
          if (typeof window !== 'undefined' && window.location.pathname !== '/login') {
            // 保存当前路径，登录后可以跳转回来
            const currentPath = window.location.pathname + window.location.search
            window.location.href = `/login?redirect=${encodeURIComponent(currentPath)}`
          }
        })
        
        return Promise.reject(new Error('未授权，请重新登录'))
      }

      // 处理 403  forbidden 错误
      if (status === 403) {
        console.warn('⚠️ [鉴权] 没有访问权限')
        return Promise.reject(new Error('没有访问权限'))
      }

      // 处理其他错误
      return Promise.reject(error)
    }
  )

  return instance
}

// 创建默认的 axios 实例（基于当前环境的 apiService）
const defaultInstance = createAxiosInstance(
  config.apiService.url,
  config.apiService.pathRewrite
)

// 封装常用的请求方法
// GET 请求
export const get = <T = any>(url: string, requestConfig?: any): Promise<T> => {
  return defaultInstance.get(url, requestConfig).then((res: AxiosResponse) => res.data)
}

// POST 请求
export const post = <T = any>(url: string, data?: any, requestConfig?: any): Promise<T> => {
  return defaultInstance.post(url, data, requestConfig).then((res: AxiosResponse) => res.data)
}

// PUT 请求
export const put = <T = any>(url: string, data?: any, requestConfig?: any): Promise<T> => {
  return defaultInstance.put(url, data, requestConfig).then((res: AxiosResponse) => res.data)
}

// DELETE 请求
export const del = <T = any>(url: string, requestConfig?: any): Promise<T> => {
  return defaultInstance.delete(url, requestConfig).then((res: AxiosResponse) => res.data)
}

// PATCH 请求
export const patch = <T = any>(url: string, data?: any, requestConfig?: any): Promise<T> => {
  return defaultInstance.patch(url, data, requestConfig).then((res: AxiosResponse) => res.data)
}

// 导出默认的 api 实例
export default defaultInstance
